package uk.ac.ebi.curtain.utils.file.fasta;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import uk.ac.ebi.curtain.utils.file.impl.AbstractChunkReader;

/**
 * File: FastaChunkReader
 * Created by: mhaimel
 * Created on: Aug 8, 2011
 * CVS:  $Id: FastaChunkReader 1.0 Aug 8, 2011 12:55:14 PM mhaimel Exp $
 */

/**
 * @author mhaimel
 *
 */
public class FastaChunkReader extends AbstractChunkReader {
	private static final char SC = '>';
	
	public FastaChunkReader(InputStream in) {
		super(in.markSupported()?in:new BufferedInputStream(in));
	}

	protected ByteArrayOutputStream _next() throws IOException {
		bo.reset();
		int c = in.read();
		if(c == -1){
			return null;
		} else if(c != SC){
			throw new IllegalStateException("Unexpected Charecter - expected char '"+SC+"' but found '" + c+"' instead!!!");
		}
		bo.write(c);
		in.mark(2);
		boolean cont = true;
		while(cont){
			c = in.read();
			switch (c) {
			case -1:
				cont = false;
				break;
			case SC:
				cont = false;
				in.reset();
				break;
			default:
				bo.write(c);
				break;
			}
			in.mark(2);
		}
		return bo;
	}

	@Override
	protected ByteBuffer _next(ByteBuffer bb) throws IOException {
		int c = in.read();
		if(c == -1){
			return null;
		} else if(c != SC){
			throw new IllegalStateException("Unexpected Charecter - expected char '"+SC+"' but found '" + c+"' instead!!!");
		}
		bb.put((byte)c);
		in.mark(2);
		boolean cont = true;
		while(cont){
			if(!bb.hasRemaining()){
				bb = increaseBuffer(bb);
			}
			c = in.read();
			switch (c) {
			case -1:
				cont = false;
				break;
			case SC:
				cont = false;
				in.reset();
				break;
			default:
				bb.put((byte)c);
				break;
			}
			in.mark(2);
		}
		return bb;
	}
	
}
